package cn.school.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

//控制不登录不给访问
@WebFilter(value = "/*", filterName = "rolef1")
public class RoleFilter implements Filter {

	@Override
	public void destroy() {
		// TODO 自动生成的方法存根

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("RoleFilter 进入了doFilter");
		try {
			// 有些地址无条件放行
			HttpServletRequest req = (HttpServletRequest) request;
			String path = req.getServletPath();// 请求地址
			if (path.equals("/LoginServlet") || path.equals("/login.jsp") || path.endsWith(".jpg")) {
				chain.doFilter(req, response);
				return;
			}
			Object o = req.getSession().getAttribute("USER_LOGIN");
			if (o == null) {
				// 没有登录
				request.setAttribute("msg", "您没有登录，不能访问这个功能");
				request.getRequestDispatcher("/login.jsp").forward(req, response);
				return;
			}
			// 其他情况，放行
			chain.doFilter(req, response);
		} finally {
			System.out.println("RoleFilter 离开了doFilter");
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO 自动生成的方法存根

	}

}
